package ar.com.jendrix.login.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.Query;

import ar.com.jendrix.common.exception.SystemException;
import ar.com.jendrix.common.util.Comparator;
import ar.com.jendrix.login.entity.Rol;
import ar.com.jendrix.login.query.RolQuery;
import ar.com.jendrix.login.type.AplicacionType;

@Stateless
public class RolDAOImpl extends LoginEntityDAO<Rol> {

	@Override
	public Class<Rol> getEntityClass() {
		return Rol.class;
	}

	@SuppressWarnings("unchecked")
	public final List<Rol> search(RolQuery rolQuery) throws SystemException {
		List<Rol> entityList = null;
		try {

			StringBuilder hql = new StringBuilder();
			hql.append("select r ");
			hql.append("from " + getEntityClass().getSimpleName() + " r ");
			hql.append("where 1 = 1 ");

			if (!Comparator.isEmpty(rolQuery.getNombre())) {
				hql.append("and upper(r.nombre) like '%" + rolQuery.getNombre().toUpperCase() + "%' ");
			}

			if (!Comparator.isEmpty(rolQuery.getAplicacion())) {
				hql.append("and r.aplicacion = :aplicacion");
			}

			hql.append("order by r.id asc");

			Query query = getEntityManager().createQuery(hql.toString());

			if (!Comparator.isEmpty(rolQuery.getAplicacion())) {
				query.setParameter("aplicacion", rolQuery.getAplicacion().name());
			}

			entityList = query.getResultList();

		} catch (Throwable t) {
			throw new SystemException(t);
		}
		return entityList;
	}

	public final boolean existeRol(AplicacionType aplicacion, String rol) throws SystemException {
		boolean existe = false;
		try {

			StringBuilder hql = new StringBuilder();
			hql.append("select count(r.id) ");
			hql.append("from " + getEntityClass().getSimpleName() + " r ");
			hql.append("where 1 = 1 ");
			hql.append("and upper(r.nombre) like '%" + rol.toUpperCase() + "%' ");
			hql.append("and r.aplicacion = :aplicacion");

			Query query = getEntityManager().createQuery(hql.toString());
			query.setParameter("aplicacion", aplicacion);

			existe = ((Long) query.getSingleResult()) > 0;

		} catch (Throwable t) {
			throw new SystemException(t);
		}
		return existe;
	}
}